package com.example.android.ui.system

import com.example.android.data.api.HomeService
import com.example.android.data.bean.SystemList
import com.example.android.http.HttpCallBack
import com.example.android.http.Result
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.sendBlocking
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

/**
 * @author zjc
 * @date 2023/10/31
 */
@ExperimentalCoroutinesApi
class SystemRepository @Inject constructor(private val service: HomeService) {

    suspend fun getSystem() = callbackFlow {
        val call = service.getSystemList()
        call.enqueue(object: HttpCallBack<List<SystemList>>() {
            override fun onSuccess(data: List<SystemList>) {
                sendBlocking(Result.Success(data))
            }

            override fun onError(code: Int, msg: String) {
                sendBlocking(Result.Error(code, msg))
            }

            override fun onComplete() {
                super.onComplete()
                //关闭流
                channel.close()
            }
        })
        awaitClose {
            call.cancel()
        }
    }

    suspend fun getSystemData() = flow<Result<Any>> {
        val response = service.getSystem()
        emit(Result.Success(response.data))
    }.catch {
        emit(Result.Error(-1, it.message ?: ""))
    }

}